<template>
  <ElementEditor v-if="type" :type="type" v-model:element="data.element" v-model:element-props="data.elementProps" />
</template>
<script lang="ts" setup>
  import { getAction, getSeed } from '@/views/seed-dev'
  import { computed, ref, watch } from 'vue';
  import { ElementConfiguration } from '@/views/dev-types';
  import { ElementEditor } from '../../ElementEditor';
  import { getRawColumns } from '../../utils/DevSeedUtil';

  const props = defineProps<{seedName?: string, actionName: string, declare: string}>()
  
  function getInitData() {
    const action = props.seedName ? getSeed(props.seedName).actions[props.actionName] : getAction(props.actionName)
    return action.elements?.[props.declare] || {element: void 0, elementProps: void 0}
  }

  const declare = ref<string>(props.declare)
  const data = ref<ElementConfiguration>(getInitData())

  const type = computed(() => {
    const seedName = props.seedName || getAction(props.actionName).seedName
    if(!seedName) return void 0
    return getRawColumns(getSeed(seedName), props.declare).type
  })
  
  function saveActionElement(seedName: string, actionName: string, declare: string, data: ElementConfiguration) {
    const action = seedName ? getSeed(seedName)?.actions?.[actionName] : getAction(actionName)
    if(!action.elements) action.elements = {}
    action.elements[declare] = data
  }

  watch([() => props.seedName, () => props.actionName, () => props.declare], () => {
    declare.value = props.declare
    data.value = getInitData()
  })

  watch(() => data.value, () => saveActionElement(props.seedName, props.actionName, declare.value, data.value), { deep: true })
</script>